<template>
    <div class="permission-container content-wrapper">
        <el-row>

            <el-col :md="6" :lg="6">
                <el-form :model="appFilter" labelPosition="right" labelWidth="80px" style="margin-bottom: 13px">
                    <el-select v-model="appFilter.appId" @change="handleChangeSelect" placeholder="所属应用" style="width: 100%;">
                        <el-option
                                v-for="item in appListOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key"
                        >
                        </el-option>
                    </el-select>
                </el-form>

                <div class="tree-header">
                    <span><i class="el-icon-mars-permission-setting" style="color:#324057"></i> 权限管理</span>
                </div>
                <el-tree :data="data" node-key="id" ref="tree"
                         v-loading="loading"
                         highlight-current
                         :check-strictly="true"
                         :default-expanded-keys="expandedKey"
                         :props="defaultProps"
                         @node-click="handleNodeClick"
                ></el-tree>
            </el-col>

            <el-col :md="18" :lg="18">
                <div class="detail-content">
                    <span class="wrapper">
                        <el-button type="primary" @click="handleCreate()">创建</el-button>
                        <el-button type="primary" @click="handleUpdate(detail)">编辑</el-button>
                        <el-button type="danger" @click="handleDelete(detail)">删除</el-button>
                        <el-button type="success" @click="handleReload">刷新</el-button>
                    </span>
                    <table>
                        <tr>
                            <td>所属上级：</td>
                            <td>{{detail.parentName == null ? '无上级' : detail.parentName}}</td>
                        </tr>
                        <tr>
                            <td>名称：</td>
                            <td>{{detail.name}}</td>
                        </tr>
                        <tr>
                            <td>编码：</td>
                            <td>{{detail.code}}</td>
                        </tr>
                        <tr>
                            <td>状态：</td>
                            <td>{{detail.status | statusFilter}}</td>
                        </tr>
                        <tr>
                            <td>排序：</td>
                            <td>{{detail.orders}}</td>
                        </tr>
                        <tr>
                            <td>备注：</td>
                            <td>{{detail.remarks}}</td>
                        </tr>
                    </table>
                </div>

                <div class="detail-content" style="margin-top: 10px">
                    <span style="display: inline-block; margin: 10px 0;">
                        <el-button type="primary" @click="handleOperatorCreate()">创建</el-button>
                    </span>

                    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">

                        <el-table-column label="ID" width="65" align="center">
                            <template slot-scope="scope"> {{scope.row.id}} </template>
                        </el-table-column>

                        <el-table-column label="名称" align="center">
                            <template slot-scope="scope"> {{scope.row.name}} </template>
                        </el-table-column>

                        <el-table-column label="编码" align="center">
                            <template slot-scope="scope"> {{scope.row.code}} </template>
                        </el-table-column>

                        <el-table-column label="状态" align="center">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.status | statusTagFilter">{{scope.row.status | statusFilter}}</el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column label="排序" align="center">
                            <template slot-scope="scope"> {{scope.row.orders}} </template>
                        </el-table-column>

                        <el-table-column label="操作" fixed="right" width="180px" align="center">
                            <template slot-scope="scope">
                                <el-button size="small" type="primary" icon="edit" @click="handleOperatorUpdate(scope.row)">编辑</el-button>

                                <el-button size="small" type="danger" icon="delete" @click="handleOperatorDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

            </el-col>

        </el-row>
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleCloseDialog" size="small">

            <el-row>
                <el-col :md="6" :lg="6">
                    <el-tree :data="data" node-key="id"
                             highlight-current
                             :default-expanded-keys="expandedKeyEdit"
                             :props="defaultProps"
                             @node-click="handleSetParent"></el-tree>
                </el-col>
                <el-col :md="6" :lg="6">
                    <el-form :model="form" ref="form" labelPosition="right"labelWidth="80px" style="width: 400px">
                        <el-form-item label="所属应用">
                            <el-select v-model.number="form.appId" clearable  placeholder="请选择所属应用" style="width: 100%;">
                                <el-option
                                        v-for="item in appListOptions"
                                        :key="item.key"
                                        :label="item.label"
                                        :value="item.key"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="所属上级" >
                            <el-input v-model="form.parentName" placeholder="请选择所属上级" readonly icon="close" :on-icon-click="handleIconClick"></el-input>
                        </el-form-item>
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="form.name"></el-input>
                        </el-form-item>
                        <el-form-item label="编码">
                            <el-input v-model="form.code"></el-input>
                        </el-form-item>
                        <el-form-item label="排序">
                            <el-input-number v-model="form.orders" :min="1"></el-input-number>
                        </el-form-item>

                        <el-form-item label="状态">
                            <el-radio-group v-model.number="form.status">
                                <el-radio class="radio" :label="1">正常</el-radio>
                                <el-radio class="radio" :label="2">禁用</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="备注">
                            <el-input
                                    type="textarea"
                                    :autosize="{ minRows: 2, maxRows: 4}"
                                    placeholder="请输入内容"
                                    v-model="form.remarks">
                            </el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else="" type="primary" @click="update">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogOperatorFormVisible" size="tiny" @close="handleOperatorCloseDialog">
            <el-form :model="operatorForm" ref="operatorForm" labelPosition="right" labelWidth="80px" style="width: 400px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="operatorForm.name"></el-input>
                </el-form-item>

                <el-form-item label="标识" prop="code">
                    <el-input v-model="operatorForm.code"></el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-radio-group v-model.number="operatorForm.status">
                        <el-radio class="radio" :label="1">正常</el-radio>
                        <el-radio class="radio" :label="2">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="排序">
                    <el-input-number v-model="operatorForm.orders" :min="1"></el-input-number>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入内容"
                            v-model="operatorForm.remarks">
                    </el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogOperatorFormVisible = false">取 消</el-button>
                <el-button v-if="dialogOperatorStatus == 'create'" type="primary" @click="createOperator">确 定</el-button>
                <el-button v-else="" type="primary" @click="updateOperator">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { created, updated, deleted, fetchObject, fetchList, fetchTree} from '@/api/upms/permission'
    import { fetchList as fetchAppList } from '@/api/upms/app'

    export default {
        name: 'permission',
        data() {
            return {
                loading: true,
                data: [],
                list: [],
                appListOptions: [],
                total: null,
                listLoading: false,
                defaultProps: {
                    label: 'name',
                    children: 'children'
                },
                dialogFormVisible: false,
                dialogStatus: '',
                dialogOperatorFormVisible: false,
                dialogOperatorStatus: '',
                textMap: {
                    create: '创建',
                    update: '编辑'
                },
                appFilter: {
                    appId: undefined
                },
                form: {
                    id: '',
                    pid: '',
                    appId: undefined,
                    name: '',
                    type: 1,
                    code: '',
                    status: 1,
                    orders: '',
                    remarks: '',
                    parentName: ''
                },
                detail: {
                    id: '',
                    pid: '',
                    appId: undefined,
                    name: '',
                    type: 1,
                    code: '',
                    status: '',
                    orders: '',
                    remarks: '',
                    parentName: ''
                },
                operatorForm: {
                    id: '',
                    pid: '',
                    name: '',
                    type: '2',
                    code: '',
                    status: 1,
                    orders: '',
                    remarks: ''
                },
                expandedKey: [1],
                expandedKeyEdit: [1]
            }
        },
        created() {

            this.getAppList()
        },
        filters: {
            statusFilter(status) {
                const statusArray = ['正常', '禁用']
                return statusArray[status?--status:'']
            },
            statusTagFilter(status) {
                const statusArray = ['success', 'danger']
                return statusArray[status?--status:'']
            }
        },
        methods: {
            getData(appId) {
                this.loading = true
                let query = {'type': 1, appId: appId}
                fetchTree(query).then(response => {
                    this.data = response.data
                    this.loading = false
                }).catch((error)=>{
                    console.log(error)
                    this.loading = false
                })
            },
            getAppList() {
                this.listLoading = true
                fetchAppList().then(response => {
                    for(let item of response.data.list) {
                        this.appListOptions.push({'label': item.name, 'key': item.id})
                    }
                    this.appFilter.appId = this.appListOptions[0].key
                    this.listLoading = false
                }).catch((error)=>{
                    console.log(error)
                    this.loading = false
                    this.listLoading = false
                })
            },
            handleChangeSelect(val) {
                this.getData(val)
            },
            handleNodeClick(data, node) {
                this.detail = data
                this.detail['parentName'] = node.parent.data.name


                this.operatorForm.pid = data.id
                this.getOperatorList()
            },
            handleSetParent(data, node) {

                var shut = false
                var sf = this.form

                //判断是否选择自己作为上级
                if(this.form.id == data.id) {
                    this.$message({
                        title: '提示', message: '选择所属上级有误',
                        type: 'info', duration: 2000
                    })
                    return
                }
                //判断选择的上级是否当前修改的上级
                res(node)
                function res(node) {
                    if(!shut) {
                        var n = node.parent
                        if(null != n) {
                            if(sf.id == n.data.id || sf.id == n.data.pid) {
                                shut = true
                            }
                            res(n)
                        }
                    }
                }
                if(shut == true) {
                    this.$message({
                        title: '提示', message: '选择所属上级有误',
                        type: 'info', duration: 2000
                    })
                    return
                }

                this.form = Object.assign({}, this.form)
                this.form['pid'] = data.id
                this.form['parentName'] = data.name
            },
            handleIconClick(ev) {
                this.form = Object.assign({}, this.form)
                this.form['pid'] = ''
                this.form['parentName'] = ''
                this.form.appId = this.appFilter.appId
            },
            handleCloseDialog() {
                this.resetForm()
            },
            handleOperatorCloseDialog() {
                this.resetOperatorForm()
            },
            handleReload(){
                this.getData(this.appFilter.appId)
            },
            handleCreate() {
                this.dialogFormVisible = true
                this.dialogStatus = 'create'
                this.form.appId = this.appFilter.appId
            },
            handleUpdate(data) {
                this.dialogStatus = 'update'
                fetchObject(data.id).then(response => {
                    this.dialogFormVisible = true
                    this.form = Object.assign(this.form, response.data)

                    this.form['parentName'] = data.parentName
                    this.expandedKeyEdit = [data.id]
                })
            },
            handleDelete(data) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(data.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.detail = {}
                            this.getData(this.appFilter.appId)
                            this.expandedKey = [data.pid]
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            create() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        if(this.form.pid) {
                            this.form.appId = null
                        }
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getData(this.appFilter.appId)
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                            this.expandedKey = [this.form.pid]
                        })
                    }
                })
            },
            update() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        if(this.form.pid) {
                            this.form.appId = undefined
                        }
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })

                                this.detail = Object.assign({}, this.form)
                                this.getData(this.appFilter.appId)

                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                            this.expandedKey = [this.form.pid]
                        })
                    }
                })
            },
            handleOperatorCreate() {
                this.dialogOperatorFormVisible = true
                this.dialogOperatorStatus = 'create'
            },
            handleOperatorUpdate(data) {
                this.dialogOperatorStatus = 'update'
                fetchObject(data.id).then(response => {
                    this.dialogOperatorFormVisible = true
                    this.operatorForm = Object.assign({}, response.data)
                })
            },
            createOperator() {
                this.$refs['operatorForm'].validate((valid) => {
                    if(valid) {

                        this.operatorForm = Object.assign({}, this.operatorForm)

                        created(this.operatorForm).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getOperatorList()
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogOperatorFormVisible = false
                        })
                    }
                })

            },
            updateOperator() {
                this.$refs['operatorForm'].validate((valid) => {
                    if(valid) {
                        updated(this.operatorForm).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getOperatorList()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogOperatorFormVisible = false
                        })
                    }
                })
            },
            handleOperatorDelete(row) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getOperatorList()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            getOperatorList() {
                this.listLoading = true
                fetchList({'pid': this.operatorForm.pid, 'type': 2}).then(response => {
                    this.list = response.data.list
                    this.listLoading = false
                }).catch(()=>{
                    this.listLoading = false
                })

            },
            resetForm() {
                this.$refs['form'].resetFields()
                this.form = {
                    id: '',
                    pid: '',
                    appId: undefined,
                    name: '',
                    type: 1,
                    code: '',
                    status: 1,
                    orders: '',
                    remarks: '',
                    parentName: ''
                }
            },
            resetOperatorForm() {
                this.$refs['operatorForm'].resetFields()
                this.operatorForm = {
                    id: '',
                    pid: this.operatorForm.pid,
                    name: '',
                    type: 2,
                    code: '',
                    status: 1,
                    orders: '',
                    remarks: ''
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .tree-header{
        height: 50px;
        border-top:1px solid #d1dbe5;
        border-left:1px solid #d1dbe5;
        border-right:1px solid #d1dbe5;
        background: #eef1f6;
        span{
            display: block;
            height: 50px;
            padding-left: 5px;
            line-height: 50px;
        }
    }
    .detail-content {
        padding-left: 20px;
        .wrapper {
            display: flex;
            justify-content: flex-start;
            margin-bottom: 10px;
            border-bottom: 1px solid #d1dbe5;
            button {
                margin-bottom: 15px;
            }
        }
        table {

        }
    }
</style>